<?php

namespace app\service;

use app\exception\ModelEmptyException;
use app\exception\TableExistException;
use app\model\Module;
use app\scaffold\ModelCreator;
use think\facade\Db;

class ModuleService
{
    protected $module;
    protected $modelCreator;

    public function __construct()
    {
        $this->module = new Module();
    }

    /**
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws ModelEmptyException
     */
    public function destroy($param): array
    {
        $module = $this->module->with(['category','moduleField'])->where($param)->find();
        if(empty($module)){
            throw new ModelEmptyException('模型不存在');
        }

        if($module['is_system'] == 1){
            return dataReturn(50013,'系统模型不能删除');
        }
        if(count($module['category'])){
            return ['code'=> 50012,'msg' => '模型有关联的栏目，不能直接删除'];
        }
        // 删除模型数据表
        $modelCreator = new ModelCreator($module['table'],$module['title']);

        Db::startTrans();
        try {
            $modelCreator->destroy();
            //删除模型表数据
            $module->together(['moduleField'])->delete();
            // 删除模型文件
            Db::commit();
        } catch (\Exception $e) {
            $modelCreator->create($module['table']);
            Db::rollback();
            return dataReturn(50014,$e->getMessage());
        }
        return dataReturn(0,'模型删除成功');
    }

    /**
     * 模型新增保存
     *
     * @param array $params
     * @return array
     * @throws \Exception
     */
    public function save(array $params): array
    {
        $modelCreator = new ModelCreator($params['table'],$params['title']);
        try{
            $path = [];
            // create table and model
            $path['model'] = $modelCreator->create();
            // create model log
            $this->module->addModule($params);

        }catch(TableExistException $e){
            return dataReturn($e->getCode(),$e->getMessage());
        } catch(\Exception $e){
            $modelCreator->dropTable($params['database_table']);
            $this-> deleteFile($path);
            return dataReturn(-50010,$e->getMessage());
        }
        return dataReturn(0,'模型创建成功');
    }

    /**
     * Delete the file at a given path.
     *
     * @param  string|array  $paths
     * @return bool
     */
    public function deleteFile($paths): bool
    {
        $paths = is_array($paths) ? $paths : func_get_args();

        $success = true;

        foreach ($paths as $path) {
            try {
                if (! @unlink($path)) {
                    $success = false;
                }
            } catch (\Exception $e) {
                $success = false;
            }
        }

        return $success;
    }
}